package org.sunflower.aliyun.oss;

import com.aliyun.oss.OSS;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.sunflower.aliyun.AliyunProperties;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * @description: Aliyun对象存储Oss相关
 * @author: TanJingyu
 * @create: 2021-10-11 18:50
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class OssService {
    private final OSS oss;
    private final AliyunProperties.Oss properties;

    /**
     * 将网络资源转存到阿里云
     * @param sourceUrl 网络资源地址
     * @param key 资源落在bucketName所指定的bucket中的全路径文件名(不能包含Bucket名称)
     */
    public void transferFromUrl (String sourceUrl, String key) throws IOException {
        this.transferFromUrl(sourceUrl, properties.getBucketName(), key);
    }

    /**
     * 将网络资源转存到阿里云
     * @param sourceUrl 网络资源地址
     * @param bucketName 阿里云oss中bucketName
     * @param key 资源落在bucketName所指定的bucket中的全路径文件名(不能包含Bucket名称)
     */
    public void transferFromUrl(String sourceUrl, String bucketName, String key) throws IOException {
        try(InputStream inputStream = new URL(sourceUrl).openStream()) {
            oss.putObject(bucketName, key, inputStream);
            oss.shutdown();
        }catch (IOException e) {
            log.error("未找到网络资源：{}", sourceUrl);
            throw e;
        }
    }
}
